import * as TYPES from '../action-types';
import { getSliders, getLessons } from "@/api/home";
import { SET_LESSONS_LOADING } from '../action-types';
import { StoreGetState, StoreDispatch } from "../index";


export default {
    setCurrentCategory(currentCategory: string) {
        return {
            type: TYPES.SET_CURRENT_CATEGORY,
            payload: currentCategory
        }
    },
    getSliders() {
        return {
            type: TYPES.GET_SLIDERS,
            payload: getSliders()
        }
    },
    getLessons() {
        return (dispatch: StoreDispatch, getState: StoreGetState) => {
            (async function () {
                let {
                    currentCategory,
                    lessons: {
                        hasMore,
                        offset,
                        limit,
                        loading
                    }
                } = getState().home;
                if (hasMore && !loading) {
                    dispatch({
                        type: TYPES.SET_LESSONS_LOADING,
                        payload: true
                    });
                    console.log(offset,
                        limit, '请求 offset,limit 从仓库获取')
                    let result = await getLessons(
                        currentCategory, offset,
                        limit,
                    );
                    console.log(result, '请求的数据。')
                    dispatch({
                        type: TYPES.SET_LESSONS,
                        payload: result.data
                    })
                }
            })()
        }
    },

    refreshLessons() {
        return async (dispatch: StoreDispatch, getState: StoreGetState) => {
            let {
                currentCategory,
                lessons: { limit, loading },
            } = getState().home;
            if (!loading) {
                dispatch({
                    type: TYPES.SET_LESSONS_LOADING,
                    payload: true
                });
                let result = await getLessons(
                    currentCategory,
                    0, limit
                );
                dispatch({
                    type: TYPES.REFRESH_LESSONS,
                    payload: result.data
                })
            }
        }
    }
}

